package top.happyone.security.demo.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import top.happyone.security.demo.mapper.AdminMapper;
import top.happyone.security.demo.pojo.Admin;


@Component
public class MyUserDetailService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailService.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        logger.info("登录用户名 :" + username);
        //logger.info("密码:" + passwordEncoder.encode("123"));
        Admin admin = new Admin().setAdminName(username);

        if ((admin = adminMapper.selectOne(admin)) == null) {
            throw new UsernameNotFoundException("没有该用户");
        }
        return new User(username, admin.getPassword(), true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,ROLE_USER"));

    }
}
